package learnnet.httpclient;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import com.liyuncong.application.commontools.FileTools;

public class SimpleHttpClient {
	/**
	 * 
	 * @param urlWithParams url字符串
	 * @param fromCharsetName 指定的输入流使用的的字符编码集
	 * @param os 用于接收输入流的输出流
	 * @param toCharsetName 输出流的字符编码集
	 * @return 请求成功返回true，否则返回false
	 */
	public static boolean requestGet(String urlWithParams, String fromCharsetName,OutputStream os, String toCharsetName){
		try (CloseableHttpClient httpclient = HttpClientBuilder.create()
				.build();) {
			HttpGet httpget = new HttpGet(urlWithParams);
			// 配置请求的超时设置
			RequestConfig requestConfig = RequestConfig.custom()
					.setConnectionRequestTimeout(5000).setConnectTimeout(5000)
					.setSocketTimeout(5000).build();
			httpget.setConfig(requestConfig);

			CloseableHttpResponse response = httpclient.execute(httpget);
			
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode != HttpStatus.SC_OK) {
				return false;
			}
			
			HttpEntity entity = response.getEntity();
			InputStream is = entity.getContent();
			FileTools.transfer(is, os, Charset.
					forName(fromCharsetName), Charset.
					forName(toCharsetName));

			httpget.releaseConnection();
			return true;
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;

	}
	
	/**
	 * get请求，自动分析出输入流的字符编码集。
	 * @param urlWithParams url字符串
	 * @param os 用于接收输入流的输出流
	 * @param toCharsetName 输出流的字符编码集
	 * @return 请求成功返回true，否则返回false
	 */
	public static boolean requestGet(String urlWithParams, OutputStream os, String toCharsetName) {
		try (CloseableHttpClient httpclient = HttpClientBuilder.create()
				.build();) {
			HttpGet httpget = new HttpGet(urlWithParams);
			// 配置请求的超时设置
			RequestConfig requestConfig = RequestConfig.custom()
					.setConnectionRequestTimeout(5000).setConnectTimeout(5000)
					.setSocketTimeout(5000).build();
			httpget.setConfig(requestConfig);

			CloseableHttpResponse response = httpclient.execute(httpget);
			
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode != HttpStatus.SC_OK) {
				return false;
			}
			
			HttpEntity entity = response.getEntity();
			String fromCharsetName = getCharsetName(entity);
			InputStream is = entity.getContent();
			if (fromCharsetName.equals("")) {
				fromCharsetName = "utf-8";
			}
			FileTools.transfer(is, os, Charset.
					forName(fromCharsetName), Charset.
					forName(toCharsetName));

			httpget.releaseConnection();
			return true;
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}
	
	/**
	 * 从entity中寻找charset
	 * @param entity
	 * @return 如果找到，就返回，否则返回空串
	 */
	private static String getCharsetName(HttpEntity entity) {
		String charsetName = "";
		String contentType = entity.getContentType().
				getValue();
		int indexOfCharset = -1;
		if (contentType != null && (indexOfCharset = 
				contentType.indexOf("charset=")) != -1) {
			charsetName = contentType.substring(
					indexOfCharset + 8);
		}
		return charsetName;
	}

	public static void requestPost(String url, List<NameValuePair> params){
		try (CloseableHttpClient httpclient = HttpClientBuilder.create()
				.build();) {
			HttpPost httppost = new HttpPost(url);
			HttpEntity httpEntity = new UrlEncodedFormEntity(params);
			httppost.setEntity(httpEntity);

			CloseableHttpResponse response = httpclient.execute(httppost);
			System.out.println(response.toString());

			HttpEntity entity = response.getEntity();
			String jsonStr = EntityUtils.toString(entity, "utf-8");
			System.out.println(jsonStr);

			httppost.releaseConnection();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
